<?php

/**
 * Description of Team
 *
 * @author Marko
 */
class Team_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    function team_id_from_full_name($full_name) {
        $result = mysql_query("SELECT `id` FROM `teams` WHERE `full_name`='$full_name'");
        if (mysql_num_rows($result) == 0) {
            return 0;
        }
        return mysql_result($result, 0);
    }

    function team_from_full_name($full_name) {
        $result = mysql_query("SELECT `id`,`full_name`,`short_name`,`abbr` FROM `teams` WHERE `full_name`='$full_name'");
        if (mysql_num_rows($result) == 0) {
            return null;
        }
        return mysql_fetch_array($result);
    }

    function team_from_id($id) {
        $result = mysql_query("SELECT `id`,`full_name`,`short_name`,`abbr` FROM `teams` WHERE `id`='$id'");
        if (mysql_num_rows($result) == 0) {
            return null;
        }
        $row = mysql_fetch_assoc($result);
        return new Team($row['full_name'], $row['short_name'], $row['abbr']);
    }

    function team_full_name_from_id($id) {
        $result = mysql_query("SELECT `full_name` FROM `teams` WHERE `id`=$id");
        return mysql_result($result, 0);
    }

    function team_name_exists($full_name) {

        $result = mysql_query("SELECT COUNT(`id`) FROM `teams` WHERE `full_name`='$full_name'") or die(mysql_error());
        return mysql_result($result, 0) == 1;
    }

    function team_exists($full_name, $short_name, $abbr) {

        $result = mysql_query("SELECT COUNT(`id`) FROM `teams` WHERE `full_name`='$full_name' and `short_name`='$short_name' and `abbr`='$abbr'") or die(mysql_error());
        return mysql_result($result, 0) == 1;
    }

    public function exists_team($full_name, $short_name, $abbr) {
        $this->db->select('id');
        $this->db->from('teams');
        $this->db->where('full_name', trim($full_name));
        $this->db->where('short_name', trim($short_name));
        $this->db->where('abbr', trim($abbr));
        $query = $this->db->get();
        if ($query->num_rows() == 0)
            return false;
        return $query->row(0)->id;
    }

    function fetchAll($array = false) {
        $this->db->select('`id`,`full_name`,`short_name`,`abbr`');
        $this->db->from('teams');
        $this->db->order_by('full_name');
        $query = $this->db->get();
        if ($array === true) {
            return $query->result_array();
        }
        return $query->result('Team');
    }

    function fetchAllLikeJson() {
        $this->db->select('`id` as team_no,`full_name`,`short_name`,`abbr`');
        $this->db->from('teams');
        $this->db->order_by('full_name');
        $query = $this->db->get();
        return $query->result_array();
    }

    function load_conflicted_teams() {
        $result = mysql_query("SELECT `id`,`full_name`,`short_name`,`abbr` FROM `teams` order by `full_name`");
        $teams = array();
        $conflicts = array();
        while ($row = mysql_fetch_assoc($result)) {
            $teams[] = Team::fromRow($row);
        }

        $n = count($teams);
        $found_conflicts = array();
        for ($i = 0; $i < $n; $i++) {
            $team1 = $teams[$i];
            $lhs = $team1->getFullName();
            $conflict = array();
            $conflict[] = $team1;
            if (in_array($lhs, $found_conflicts))
                continue;
            for ($j = 0; $j < $n; $j++) {
                $team2 = $teams[$j];
                $rhs = $team2->getFullName();
                similar_text($lhs, $rhs, $p);
                if ($i !== $j && $p > 90 && !in_array($rhs, $found_conflicts)) {
                    $found_conflicts[] = $lhs;
                    $conflict[] = $team2;
                    //echo '<br><br>' . $team1 . ' - ' . $team2 . ' ' . $p . '%';
                }
            }
            if (count($conflict) > 1) {
                $conflicts[] = $conflict;
            }
        }
        return $conflicts;
    }

    function print_conflicted_teams() {

        $conflicts = load_conflicted_teams();

        if (count($conflicts) === 0) {
            table_from_teams();
        } else {
            ?>
            <h2>Leitud konfliktid</h2>
            <form action = "fix_conflicts.php" method = "post">
                <table class="klubid">
                    <tr>
                        <th>Valik</th>
                        <th>#</th>
                        <th>Nimi</th>
                        <th>Lühendatud nimi</th>
                        <th>Lühend</th>
                        <th>Sportlasi</th>
                    </tr>

                    <?php
                    for ($i = 0; $i < count($conflicts); $i++) {
                        $max_count = 0;
                        foreach ($conflicts[$i] as $team) {
                            $count = athletes_count_for_team($team->getID());
                            echo '<tr>';
                            echo '<td><input type="radio" name="conflicted_teams' . $i . '" value="' . $team->getID() . '"';
                            if ($count > $max_count) {
                                echo 'checked></td>';
                                $max_count = $count;
                            } else {
                                echo '></td>';
                            }
                            echo '<td>' . $i . '</td>';
                            echo $team->toTableColumns();
                            echo '<td>' . $count . '</td>';
                            echo '</tr>';
                        }
                        echo '</tr><tr><td colspan = "4">&nbsp;
                            </td></tr>';
                    }
                    ?>
                    <input type="hidden" name="conflicted_teams_size" value="<?php echo count($conflicts) ?>">
                </table>
                <input type="submit" name="fix_team_conflicts" value="Paranda konfliktid"> 
            </form>
            <?php
        }
    }

    function print_found_teams($teams, $file_name) {
        $teams_old = array();
        $teams_new = array();
        foreach ($teams as &$team) {
            if (team_exists($team->getFullName(), $team->getShortName(), $team->getAbbr())) {
                $teams_old[] = $team;
            } else {
                $teams_new[] = $team;
            }
        }

        echo '<table class = "klubid">';
        echo '<tr><th colspan = "3"><h2>Uued klubid</h2></th></tr><tr><th>Nimi</th><th>Lühendatud nimi</th><th>Lühend</th></tr>';

        if (count($teams_new !== 0)) {
            ?>
            <form action = "getfile.php" method = "post">
                <input type="hidden" value="<?php echo $file_name ?>" name="file_name">
                <input type="submit" value = "Lisa uued klubid" name="add_teams"><?php
            foreach ($teams_new as $team) {
                echo $team->toTableRow();
            }
            echo '</table>';
        } else {
            echo 'Ühtegi uut klubi ei leitud<br>';
        }
        echo '<table class = "klubid">';
        echo '<tr><th colspan = "3"><h2>Olemasolevad klubid</h2></th></tr><tr><th>Nimi</th><th>Lühendatud nimi</th><th>Lühend</th></tr>';


        foreach ($teams_old as $team) {
            echo $team->toTableRow();
        }
        echo '</table>';
    }

    function insert_teams_to_db($teams) {

        $query = "INSERT INTO `teams`(`full_name`, `short_name`, `abbr`) VALUES ";
        $fields = '';
        foreach ($teams as $team) {
            if (!$this->team_exists($team->getFullName(), $team->getShortName(), $team->getAbbr())) {
                $array = $team->toArray();
                unset($array['id']);
                $fields .= '(\'' . implode('\', \'', $array) . '\'), ';
            }
        }
        $query .= substr($fields, 0, strlen($fields) - 2);

//        echo $query;
        mysql_query($query) or die(mysql_error());
    }

    public function insertNewTeams($teams) {
        $this->db->ignore();
        foreach ($teams as &$team) {
            unset($team['team_no']);
        }
        $this->db->insert_batch('teams', $teams);
    }

    public function teams_from_mdb($mdb) {
        $teams = $mdb->select('Team_name as full_name, Team_abbr as abbr, Team_short as short_name')->from('Team')->get()->result('Team');
        Utils::utf8_encode_deep($teams);
        Utils::trim_deep($teams);
        return $teams;
    }

    function team_from_xml($data) {
        if (!empty($data)) {
            $i = 0;
            $team = new Team();
            do {
                $object = $data->FormattedArea[0]
                        ->FormattedSections[0]->FormattedSection[0]
                        ->FormattedReportObjects[0]
                        ->FormattedReportObject[$i];

                if (empty($object)) {
                    if ($team->getFullName() == NULL)
                        return null;

                    if ($team->getShortName() == NULL) {
                        $team->setShortName('');
                    }
                    if ($team->getAbbr() == NULL) {
                        $team->setAbbr('');
                    }
                    return $team;
                };

                $result = $object->ObjectName;
                switch ($result) {
                    case 'Teamname1':
                        $team->setFullName(strval($object->Value));
                        break;
                    case 'Teamabbr1':
                        $team->setAbbr(strval($object->Value));
                        break;
                    case 'Teamshort1':
                        $team->setShortName(strval($object->Value));
                        break;
                    default:
                        break;
                }
                $i++;
            } while ($i < 10);
        }
    }

    function teams_from_xml_path($path_to_xml) {
        $teams = array();
        $results_xml = simplexml_load_file($path_to_xml);
        $j = 0;
        do {
            $data = $results_xml->FormattedAreaPair[0]->FormattedAreaPair[$j];
            $j++;
            $team = $this->team_from_xml($data);
            if ($team != null) {
                $teams[] = $team;
            }
            // max 500 inserts at a time.
        } while (!empty($data) && $j < 500);
        return $teams;
    }

}
?>
